#include "chan.h"
#include "thread.h"

#include "mem.h"

#include <stdio.h>
#include <string.h>
#include <assert.h>

static const char *str = "hello, world";

static int
func1(void *arg)
{
    Chan_T c = *(Chan_T*)arg;
    int n = Chan_send(c, str, strlen(str));
    printf("func1: send %d\n", n);
    assert(n == (int)strlen(str));

    char buf[1024];
    n = Chan_receive(c, buf, sizeof(buf));
    buf[n] = '\0';
    printf("func1:receive %d - %s\n", n, buf);
    assert(strcmp(buf, str) == 0);
    return 0;
}

static int
func2(void *arg)
{
    Chan_T c = *(Chan_T*)arg;
    char buf[1024];
    int n = Chan_receive(c, buf, sizeof(buf));
    buf[n] = '\0';
    printf("func2:receive %d - %s\n", n, buf);
    assert(strcmp(buf, str) == 0);

    n = Chan_send(c, str, strlen(str));
    printf("func2: send %d\n", n);
    assert(n == (int)strlen(str));
    return 0;
}


static void
test()
{
    Chan_T c = Chan_new();
    Thread_new(func1, &c, (int)sizeof(c));
    Thread_new(func2, &c, (int)sizeof(c));
    Thread_join(NULL);
    FREE(c);
}

int main()
{
    Thread_init(0);
    test();
    printf("main exit now!\n");
    Thread_exit(0);
    return 0;
}

